#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件    :Untitled-3
@说明    :
@时间    :2020/05/11 00:18:13
@作者    :王舰航
@版本    :3.0
'''

# 给定一组数据网址数据，请判断这些网址是否可以访问； 用多线程的方式来实现；
#    请查资料，Python的 requests库，如何判断一个网址可以访问；

import requests, threading

def getHtmlText(url):
    try:        # 网络连接有风险，异常处理很重要
        r = requests.get(url,timeout=30)
        r.raise_for_status()   # 如果状态不是200，引发HTTPError异常
        r.encoding = r.apparent_encoding
        # return r.text
        return '>>>>>>Successfully visited: ' + url
    except:
        return url + " 产生异常"

class JudgeThread( threading.Thread ):

    url_list = []

    def __init__( self, url_list ):
        # super( self ).__init__()
        threading.Thread.__init__( self )
        self.url_list = url_list

    def run( self ):
        for url in self.url_list:
            print( '>>>>%s is running: %s' %( self.name, getHtmlText( url ) ) )


if __name__ == "__main__":

    all_urls = []
    with open( 'url_data.txt', 'r', encoding = 'utf-8' ) as f:
        for line in f.readlines():
            all_urls += line.strip().split( '; ' )
    
    url_list1 = all_urls[ 0 : int( len(all_urls) / 3 ) - 1 ]
    url_list2 = all_urls[ int( len(all_urls) / 3 ) : int( 2 * len(all_urls) / 3 ) - 1 ]
    url_list3 = all_urls[ int( 2 * len(all_urls) / 3 ) : int( 3 * len(all_urls) / 3 ) - 1 ]

    t1 = JudgeThread( url_list1 )
    t2 = JudgeThread( url_list2 )
    t3 = JudgeThread( url_list3 )

    t1.start()
    t2.start()
    t3.start()